﻿Imports System.Data
Imports ADOEntityKYC

Partial Class Administrator_frmProvince
    Inherits Web.UI.BasePage
    Private Const strMenuCode As String = "M74"
    Dim sProvinceEntity As KYCEntities
    Dim dsProvince As New DataSet
    Dim clsQuery As clsDatabase
    Dim clsDataTable As New clsLINQToDataTable
    Dim intBeforeItemIndex As Integer
    Dim clsSessionMenuRight As clsSessionMenuRight = New clsSessionMenuRight
    Dim strMsg As String = ""
#Region " Even Page "

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        lblProvinceCode.Text = "รหัสจังหวัด" & " : "
        lblProvinceName.Text = "ชื่อจังหวัด" & " : "

        btnSearch.Text = Resources.resButton.btnSearch
        btnAdd.Text = Resources.resButton.btnAdd
        btnModify.Text = Resources.resButton.btnModify
        btnDelete.Text = Resources.resButton.btnDelete
        btnClear.Text = Resources.resButton.btnClear

        lblMsg.Text = Resources.resMessageAlert.alertEmptyGrid
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            chkIsLogin()
            clsSessionMenuRight = Session("clsMenuRight")

            If (Not IsPostBack) Then
                setUserRightButton()
                CreateControlMP()
                setButton(1)
            Else
                dsProvince = Session("dsTblMaster")
                gvProvince.DataSource = dsProvince.Tables("sProvince")
                gvProvince.DataBind()
            End If
        Catch ex As Exception

        End Try


    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        Session("dsTblMaster") = dsProvince
    End Sub

#End Region

#Region "SetForm"

    Sub CreateControlMP()

        Dim lblForm As Label = CType(Master.FindControl("lblForm"), Label)
        lblForm.Text = "จังหวัด"
    End Sub

#End Region

#Region " Even Button "

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        IsDataBind()
        clearGvIndex()
        SaveLogSearch()
    End Sub

    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        ' Response.Redirect("Department.aspx?Status=Add")

        Try
            If chkBeforeSave() Then
                sProvinceEntity = New KYCEntities
                Dim sProvince As New REFERENCE_CODE_TABLE
                sProvince.RCRE_TIME = Now
                sProvince.LCHG_TIME = Now
                sProvince.LCHG_USER_ID = clsSessionMenuRight.getUserName
                sProvince.RCRE_USER_ID = clsSessionMenuRight.getUserName
                sProvince.REF_CODE = txtProvinceCode.Text
                sProvince.REF_DESC = txtProvinceName.Text
                sProvince.REF_REC_TYPE = "03"
                sProvince.DEL_FLG = "N"
                sProvinceEntity.AddToREFERENCE_CODE_TABLE(sProvince)
                sProvinceEntity.SaveChanges()

                SaveLogNew()

                IsDataBind()
                reset()

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resMsgKYC.msgSave + "')", True)

            Else

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + strMsg + "')", True)

            End If
        Catch ex As System.Data.UpdateException

            Dim codeError() As String = ex.InnerException.Message.Split(":")
            If codeError(0) = "ORA-00001" Then
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('ไม่สามารถเพิ่มได้ เนื่องจากรหัสนี้มีการนำมาใช้ในระบบแล้ว')", True)
            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
            End If
            WriteError(ex, "btnAdd_Click", "Province")
        Catch ex As Exception
            WriteError(ex, "btnAdd_Click", "Province")
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('บันทึกผิดพลาด')", True)

        End Try
    End Sub

    Protected Sub btnModify_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnModify.Click
      

        Try
            If chkBeforeSave() Then
                sProvinceEntity = New KYCEntities
                Dim sProvince As New REFERENCE_CODE_TABLE

                Dim qry = (From province In sProvinceEntity.REFERENCE_CODE_TABLE Where province.REF_CODE = txtProvinceCode.Text).ToList
                'txtPoscode.Text = qry(0).POSCODE
                qry(0).LCHG_TIME = Now
                qry(0).LCHG_USER_ID = clsSessionMenuRight.getUserName
                qry(0).REF_DESC = txtProvinceName.Text
                sProvinceEntity.SaveChanges()

                SaveLogEdit()

                IsDataBind()
                reset()

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resMsgKYC.msgSave + "')", True)

            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + strMsg + "')", True)
            End If

        Catch ex As System.Data.UpdateException
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
            WriteError(ex, "btnModify_Click", "Province")
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('บันทึกผิดพลาด')", True)
            WriteError(ex, "btnModify_Click", "Province")
        End Try


    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If Not (gvProvince.SelectedIndex = -1) Then
            Dim DepC As String = gvProvince.Rows(gvProvince.SelectedIndex).Cells(1).Text
            Try
                sProvinceEntity = New KYCEntities
                Dim qry = (From s_pro In sProvinceEntity.REFERENCE_CODE_TABLE Where s_pro.REF_CODE = DepC).ToList
                'sProvinceEntity.DeleteObject(qry(0))
                qry(0).DEL_FLG = "Y"
                sProvinceEntity.SaveChanges()

                SaveLogDelete(DepC)

                IsDataBind()
                reset()

            Catch ex As System.Data.UpdateException
                Dim codeError() As String = ex.InnerException.Message.Split(":")
                If codeError(0) = "ORA-02292" Then
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('ไม่สามารถลบได้ เนื่องจากมีการนำมาใช้ในระบบแล้ว')", True)
                Else
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
                End If
                WriteError(ex, "btnDelete_Click", "Province")
            Catch ex As Exception
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resError.errorMessage + "')", True)
                WriteError(ex, "btnDelete_Click", "Province")
            End Try

        Else
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resValidate.nonSelectGridDelete + "')", True)

        End If

    End Sub

    Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        clear()
    End Sub


#End Region

#Region "Even GridView"

    Protected Sub gvProvince_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvProvince.SelectedIndexChanged
        Try
            If (gvProvince.SelectedIndex = intBeforeItemIndex) Then
                clearGvIndex()
                reset()

                btnModify.Text = "แก้ไข"
            Else
                btnModify.Text = "บันทึก"

                setButton(2)

                txtProvinceCode.Text = gvProvince.Rows(gvProvince.SelectedIndex).Cells(1).Text
                txtProvinceName.Text = gvProvince.Rows(gvProvince.SelectedIndex).Cells(2).Text

                btnDelete.Attributes.Add("onclick", "return confirm('" + String.Format(Resources.resValidate.confirmDelete, _
                           IIf(gvProvince.SelectedIndex = -1, "", gvProvince.Rows(gvProvince.SelectedIndex).Cells(2).Text)) + "');")
            End If
        Catch ex As Exception
            WriteError(ex, "gvProvince_SelectedIndexChanged", "Province")
        End Try


    End Sub
    Protected Sub gvProvince_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles gvProvince.SelectedIndexChanging
        intBeforeItemIndex = gvProvince.SelectedIndex
    End Sub

    Protected Sub gvProvince_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvProvince.PageIndexChanging
        gvProvince.PageIndex = e.NewPageIndex
        clearGvIndex()
        DataBind()
    End Sub

    Protected Sub gvProvince_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvProvince.Sorting
        Dim dt = TryCast(dsProvince.Tables("sProvince"), DataTable)

        If dt IsNot Nothing Then

            'Sort the data.
            dt.DefaultView.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
            gvProvince.DataSource = dsProvince.Tables("sProvince")
            gvProvince.DataBind()
            clearGvIndex()
        End If
    End Sub

#End Region

#Region " Function"

    Private Sub setUserRightButton()
        Dim col As New Collection
        col.Add(btnSearch, statusbtn.Query.ToString)
        col.Add(btnAdd, statusbtn.Add.ToString)
        col.Add(btnModify, statusbtn.Modify.ToString)
        col.Add(btnDelete, statusbtn.delete.ToString)
        setBtnToUserRight(col, strMenuCode, clsSessionMenuRight.getDsMenuRight)

    End Sub
    Private Sub clearGvIndex()
        gvProvince.SelectedIndex = -1
        '  btnDelete.Attributes.Clear()
    End Sub

    Private Sub IsDataBind()
        Try


            sProvinceEntity = New KYCEntities

            If dsProvince.Tables.Contains("sProvince") Then
                dsProvince.Tables.Clear()
            End If
            Dim qryPro = From Province In sProvinceEntity.REFERENCE_CODE_TABLE
                         Where Province.REF_REC_TYPE = "03" And Province.DEL_FLG = "N"
                        Order By Province.REF_CODE
                        Select Province.REF_CODE, Province.REF_DESC

            If Not (txtProvinceCode.Text = "") Then
                qryPro = qryPro.Where(Function(Pro) Pro.REF_CODE.Contains(txtProvinceCode.Text))
            End If

            If Not (txtProvinceName.Text = "") Then
                qryPro = qryPro.Where(Function(Pro) Pro.REF_DESC.Contains(txtProvinceName.Text))
            End If

            dsProvince.Tables.Add(clsDataTable.LINQToDataTable(qryPro, "sProvince").Copy)

            If (qryPro.Count = 0) Then
                lblMsg.Visible = True
                lblTotal.Text = ""
            Else
                lblMsg.Visible = False
                lblTotal.Text = "จำนวนรายการทั้งหมด " + qryPro.Count.ToString + " รายการ "

            End If

            gvProvince.DataSource = dsProvince.Tables("sProvince")
            gvProvince.DataBind()

            clsDataTable = Nothing
        Catch ex As Exception
            WriteError(ex, "IsDataBind", "Province")

        End Try
    End Sub

    Private Function GetSortDirection(ByVal column As String) As String

        ' By default, set the sort direction to ascending.
        Dim sortDirection = "DESC"

        ' Retrieve the last column that was sorted.
        Dim sortExpression = TryCast(ViewState("SortExpression"), String)

        If sortExpression IsNot Nothing Then
            ' Check if the same column is being sorted.
            ' Otherwise, the default value can be returned.
            If sortExpression = column Then
                Dim lastDirection = TryCast(ViewState("SortDirection"), String)
                If lastDirection IsNot Nothing _
                  AndAlso lastDirection = "DESC" Then

                    sortDirection = "ASC"

                End If
            End If
        End If

        ' Save new values in ViewState.
        ViewState("SortDirection") = sortDirection
        ViewState("SortExpression") = column
        Return sortDirection
    End Function

    Private Sub setButton(ByVal button As Integer)

        If button = 1 Then 'unselect
            lblMsg.Visible = False

            btnModify.Enabled = False
            btnDelete.Enabled = False

            btnSearch.Enabled = True
            btnAdd.Enabled = True

            txtProvinceCode.Enabled = True

        ElseIf button = 2 Then 'select

            btnSearch.Enabled = False
            btnAdd.Enabled = False

            btnModify.Enabled = True
            btnDelete.Enabled = True

            txtProvinceCode.Enabled = False

        End If

    End Sub

    Private Sub clear()
        If (dsProvince.Tables.Contains("sProvince")) Then
            dsProvince.Tables("sProvince").Clear()
            gvProvince.DataSource = dsProvince.Tables("sProvince")
            gvProvince.DataBind()
        End If
        clearGvIndex()
        setButton(1)
        lblMsg.Visible = False
        txtProvinceCode.Text = ""
        txtProvinceName.Text = ""
        lblTotal.Text = ""
        btnModify.Text = "แก้ไข"
    End Sub

    Private Sub reset()
        'gvUserRight.DataSource = dsUserRight.Tables("sUserRight")
        'gvUserRight.DataBind()
        clearGvIndex()
        setButton(1)
        lblMsg.Visible = False
        txtProvinceCode.Text = ""
        txtProvinceName.Text = ""
    End Sub

    Private Function chkBeforeSave() As Boolean
        Dim result As Boolean = True

        If (txtProvinceCode.Text = "") Then
            result = False
            strMsg = strMsg & "กรุณาระบุรหัสจังหวัด" & "\n"
        ElseIf txtProvinceCode.Text.Length < 2 Then
            result = False
            strMsg = strMsg & "กรุณาระบุรหัสจังหวัดมากกว่าหนึ่งหลัก" & "\n"
        End If


        If (txtProvinceName.Text = "") Then
            result = False
            strMsg = strMsg & txtProvinceName.Text & " : " & "กรุณาระบุชื่อจังหวัด" & "\n"

        End If

        Return result

    End Function

    Private Sub SaveLogSearch()
        Try


            Dim desc As String = ""

            If Not (txtProvinceCode.Text = "") Then
                desc += " รหัสจังหวัด - " + txtProvinceCode.Text
            End If

            If Not (txtProvinceName.Text = "") Then
                desc += " ชื่อจังหวัด - " + txtProvinceName.Text
            End If


            If Not desc = "" Then
                desc = "ค้นหาข้อมูลจังหวัด จาก " + desc
            Else
                desc = "ค้นหาทั้งหมด"
            End If

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, 1, desc, "M74")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogPrint()
        Try

            Dim desc As String = "พิมพ์ข้อมูลจังหวัด"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, 2, desc, "M74")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogNew()
        Try

            Dim desc As String = "บันทึก ข้อมูลจังหวัด (รหัสจังหวัด " + txtProvinceCode.Text + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(txtProvinceCode.Text, clsSessionMenuRight.getUserName, 3, desc, "M74")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogEdit()
        Try

            Dim desc As String = "บันทึก แก้ไข ข้อมูลจังหวัด (รหัสจังหวัด " + txtProvinceCode.Text + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(txtProvinceCode.Text, clsSessionMenuRight.getUserName, 4, desc, "M74")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogDelete(ByVal value As String)
        Try

            Dim desc As String = "ลบข้อมูลจังหวัด (รหัสจังหวัด " + value + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(value, clsSessionMenuRight.getUserName, 5, desc, "M74")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

#End Region


End Class
